<template>
  <a-card>
    <a-row :gutter="24">
      <a-col :md="6" :sm="24">
        <a-card hoverable style="height:600px;overflow-y:auto">
          <a-tree :showLine="true" @expand="onExpand" :expandedKeys="expandedKeys" :autoExpandParent="autoExpandParent" v-model="checkedKeys" @select="onSelect" :selectedKeys="selectedKeys" :treeData="treeData" :replaceFields="replaceFields" />
        </a-card>
      </a-col>
      <a-col :md="18" :sm="24">
        <div class="table-page-search-wrapper" style="margin-bottom:16px">
          <a-row style="margin-bottom:16px">
            <a-col :md="16" :sm="24">
              <a-input-search @search="search" enterButton="查询" />
            </a-col>
            <a-col :md="8" :sm="24" style="text-align:right">
              <a-button type="primary" class="actionButton" @click="add">添加</a-button>
              <a-popconfirm v-if="isAdmin()" title="确定删除?" okText="确定" cancelText="取消" @confirm="del">
                <a-button type="danger" class="actionButton">删除</a-button>
              </a-popconfirm>
            </a-col>
          </a-row>
        </div>
        <a-spin :spinning="spinning" tip="获取数据中...">
          <div class="spin-content">
            <a-table size="small" bordered :rowKey="record => record.Id" :columns="columns" :dataSource="data" :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :rowClassName="setRowClassName">
              <span slot="action" slot-scope="text, record">
                <template>
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>修改</span>
                    </template>
                    <span size="small" type="link" @click="handleEdit(record)" style="cursor:pointer;color:#1890FF">修改</span>
                  </a-tooltip>
                </template>
              </span>
            </a-table>
          </div>
        </a-spin>
      </a-col>
    </a-row>
    <a-modal :title="title" :visible="visible" @cancel="handleCancel" :footer="null" :centered="true">
      <div class="waterArea" style="background-color:#fff">
        <a-spin :spinning="loading">
          <a-form :form="form">
            <a-form-item v-bind="formItemLayout" label="部门编码">
              <a-input v-decorator="['Code', { rules: [{ required: true, message: '请填写部门编码!' }] }]" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="部门名称">
              <a-input v-decorator="['DepartmentName', { rules: [{ required: true, message: '请填写部门名称!' }] }]" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="上级部门">
              <treeselect :show-count="true" :options="Dept" v-model="ParentId" placeholder="请选择工作部门..." :normalizer="normalizer" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="排序">
              <a-input v-decorator="['Sortnum', { rules: [{ required: true, message: '请填写排序!' }] }]" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="备注">
              <a-input v-decorator="['Remark']" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout1" style="text-align:center;margin-bottom:0">
              <a-button type="primary" @click="ok">确定</a-button>
            </a-form-item>
          </a-form>
        </a-spin>
      </div>
    </a-modal>
    <!-- <a-modal
      :title="'部门'"
      :visible="visibleDepart"
      :width="300"
      @cancel="handleCancelDepart"
      :footer="null"
      :centered="true"
    >
      <a-tree
        :showLine="true"
        @expand="onExpand"
        :expandedKeys="expandedKeys"
        :autoExpandParent="autoExpandParent"
        v-model="checkedKeys"
        @select="onSelect"
        :selectedKeys="selectedKeys"
        :treeData="treeData"
        :replaceFields="replaceFields"
      />
      <a-button type="primary" @click="okDepart">确定</a-button>
    </a-modal>-->
  </a-card>
</template>

<script>
import { saveDepartment, getDepartmentList, deleteDepartment, getDepartmentByTypeSettings, getDepartmentById, deleteDepartments } from '@/api/department'
import { deleteChildrenIfNull } from '@/utils/util'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import '@/views/treeselect1.css'
import { authDevice } from '@/utils/mixin'
export default {
  mixins: [authDevice],
  components: {
    Treeselect
  },
  data() {
    return {
      title: '添加部门',
      visible: false,
      visibleDepart: false,
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      data: [],
      selectedRowKeys: [],
      replaceFields: {
        key: 'id'
      },
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      spinning: false,
      // 表头
      columns: [
        {
          title: '部门编码',
          dataIndex: 'Code',
          key: 'Code',
          align: 'center'
        },
        {
          title: '部门名称',
          dataIndex: 'DepartmentName',
          key: 'DepartmentName',
          align: 'center'
        },
        {
          title: '排序',
          dataIndex: 'Sortnum',
          key: 'Sortnum',
          align: 'center'
        },
        {
          title: '备注',
          dataIndex: 'Remark',
          key: 'Remark',
          align: 'center'
        },
        {
          title: '操作',
          width: '150px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      loading: false,
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 }
        }
      },
      formItemLayout1: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 0 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        }
      },
      Dept: [],
      currentId: null,
      ParentId: null
    }
  },
  watch: {
    checkedKeys(val) {
      console.log('onCheck', val)
    }
  },
  created() {
    this.initTree()
    this.initData(null)
  },
  methods: {
    initTree() {
      getDepartmentList().then(res => {
        this.Dept = res.children
        this.removeChildrenIfNUll(this.Dept)
        this.treeData = res.children
      })
    },
    removeChildrenIfNUll(data) {
      data.map(a => {
        if (a && a.children.length > 0) {
          this.removeChildrenIfNUll(a.children)
        } else {
          deleteChildrenIfNull(a)
        }
      })
    },
    initData(data) {
      this.spinning = true
      getDepartmentByTypeSettings({ id: data })
        .then(res => {
          this.data = res.filter(a => a.Id !== -1)
        })
        .finally(() => {
          this.spinning = false
        })
    },
    search() {
      this.initData(null)
    },
    add() {
      this.title = '添加部门'
      this.visible = true
      this.form.resetFields()
      this.ParentId = null
    },
    ok() {
      const {
        form: { validateFields }
      } = this
      validateFields((errors, values) => {
        if (!errors) {
          this.loading = true
          setTimeout(() => {
            // console.log(this.$store.getters.token.id)
            const value = {
              ...values,
              Id: this.currentId,
              ParentId: this.ParentId
            }
            saveDepartment(value).then(res => {
              this.initData(this.selectedKeys[0])
              this.initTree()
              this.currentId = null
              this.loading = false
              this.visible = false
            })
          }, 1000)
        } else {
        }
      })
    },
    okDepart() {
      this.visibleDepart = false
    },
    del() {
      deleteDepartments(this.selectedRowKeys).then(res => {
        this.initData(this.selectedKeys[0])
        this.initTree()
        this.selectedRowKeys = []
      })
    },
    open() {
      this.visibleDepart = true
    },
    handleEdit(data) {
      this.title = '修改部门'
      getDepartmentById({ depId: data.Id }).then(res => {
        this.visible = true
        setTimeout(() => {
          this.ParentId = data.ParentId
          this.currentId = data.Id
          this.form.setFieldsValue({ Code: data.Code })
          this.form.setFieldsValue({ DepartmentName: data.DepartmentName })
          this.form.setFieldsValue({ Remark: data.Remark })
          this.form.setFieldsValue({ Sortnum: data.Sortnum })
        }, 500)
      })
    },
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onCheck(checkedKeys) {
      console.log('onCheck', checkedKeys)
      this.checkedKeys = checkedKeys
    },
    onSelect(selectedKeys, e) {
      this.ParentId = e.selectedNodes[0].data.props.name
      // this.form.setFieldsValue({ ParentName: this.ParentName })
      console.log(e.selectedNodes)
      this.selectedKeys = selectedKeys
      this.ParentId = selectedKeys[0]
      this.initData(selectedKeys[0])
    },
    handleCancel() {
      this.visible = false
    },
    handleCancelDepart() {
      this.visibleDepart = false
    },
    setRowClassName(record, idx) {
      return idx % 2 == 1 ? 'bg-row' : ''
    }
  }
}
</script>

<style lang="less" scoped>
.actionButton {
  margin-left: 10px;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.tree-select-label-YH {
  display: inline-block;
  height: 30px;
  vertical-align: bottom;
  text-align: right;
}
.tree-select-self-YH {
  display: inline-block;
  width: 200px;
  margin-left: 8px;
}
</style>
